package com.shop.controller;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.jf.core.AuthInterceptor;
import com.jf.core.BaseController;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.shop.bean.AddressBean;
import com.shop.bean.LiuyanBean;
import com.shop.bean.UserBean;
import com.shop.bean.UserInfoBean;
import com.shop.bean.XfjfBean;
import com.shop.utils.MD5Utils;
import com.shop.utils.StringUtils;

/**
 * 前台  用户控制器类
 * @author bsh_2012@163.com
 *
 */
public class CUserController extends BaseController {

	/**
	 * 注册页面
	 */
	public void regpage(){
		render(WIEW_WEB+"register-.jsp");
	}
	
	/**
	 * 登录页面
	 */
	public void lgnpage(){
		render(WIEW_WEB+"login-.jsp");
	}
	
	/**
	 * 注销
	 */
	public void lgnout(){
		setSessionAttr("user", null);
		getSession().removeAttribute("user");
		setSessionAttr("url", null);
		getSession().removeAttribute("url");
		redirect(getRequest().getContextPath()+"/wlc/index?url="+StringUtils.getTimeCode());
	}
    /**
     * 验证用户名是否存在
     * */
	public void ValUserName(){
		String username = getPara("username");
		String sql_ = StringUtils.getSql("sql.find.findUserInfoByUserName", username);
		UserBean user = UserBean.dao.findFirst(sql_);
		if(user == null){
			renderJson("message","true");
		}else{
			renderJson("message","false");
		}
	}
	
	/**
	 * 新用户注册
	 */
	public void reg(){
		
		final String username = getPara("username");
		final String encry = getPara("encry");
		final String md5password = getPara("md5password");
		boolean bool = Db.tx(new IAtom(){
			@Override
			public boolean run() throws SQLException {
				UserBean user  = new UserBean();
				boolean b1 = user
							.set("ucode", StringUtils.getTimeCode())
							.set("uname", username)
							.set("upass", md5password)
							.set("uencry",encry)
							.set("ujuese", 0)	//普通用户
							.set("zctime", StringUtils.getFormatTime(new Date()))
							.set("lasttime", StringUtils.getFormatTime(new Date()))
							.save();
				UserInfoBean userInfo = new UserInfoBean();
				boolean b2 = userInfo
						     .set("mcode", StringUtils.getTimeCode())
						     .set("ucode", user.get("ucode"))
						     .set("ustate", 1)
						     .save();
				boolean b3 = new XfjfBean()
				             .set("xfcode", StringUtils.getTimeCode())
				             .set("ucode", user.get("ucode"))
				             .set("jifen", 0)
				             .save();
				if(b1 && b2 && b3){
					logger.info("新用户："+user);
					setSessionAttr("user", user);
				}
				return b1 && b2 && b3;
			}
		});
		if(bool){
//			render("/index.jsp");
//			redirect(getRequest().getContextPath()+"/index.jsp");
			redirect(getRequest().getContextPath()+"/wlc/index?url="+StringUtils.getTimeCode());
		}else{
			forwardAction("/urc/regpage");
		}
	}
	
	/**
	 * 用户登录
	 */
	public void lgn(){
		String uname = getPara("username");
		
		String pwd = getPara("pwd");
		String sql = StringUtils.getSql("sql.find.findUserInfoByUserName",uname);
		UserBean user = UserBean.dao.findFirst(sql);  // ujuese = 0 是普通用户
		if(user !=null && "0".equals(user.getStr("ujuese")) && MD5Utils.makeMD5Password(pwd, user.getStr("uencry"))
						.equals(user.getStr("upass"))){
			logger.info("用户登录："+uname);
			setSessionAttr("user", user);
			setSessionAttr("uname", user.getStr("uname"));
			user.set("lasttime", StringUtils.getFormatTime(new Date())).update();
			
			forwardAction("/crtc/peristShoppingCartWhenUserLogin");
		//	redirect(getRequest().getContextPath()+"/crtc/peristShoppingCartWhenUserLogin");
			//redirect(getRequest().getContextPath()+"/wlc/index?url="+StringUtils.getTimeCode());
		}else{
			renderHtml("<script>alert('用户名或密码错误');history.back();</script>");
		}
		
		
	}
	
	/**
	 * 验证用户名是否存在
	 */
	public void regusername(){
		String username = getPara("username");
		String sql = StringUtils.getSql("sql.find.findUserInfoByUserName",username);
		UserBean user = UserBean.dao.findFirst(sql);
		if(user != null){
			renderJson("message","false");
		}else{
			renderJson("message","true");
		}
	}
	

	
	
///-----------用户中心-----------------------------------------------------------------//	
	//用户中心
	public void center(){
		UserBean user = getSessionAttr("user");
		String ucode =  user.get("ucode");
		String sql_ = StringUtils.getSql("sql.find.findUserInfoByCode",ucode);
		UserInfoBean userInfo = UserInfoBean.userInfoDao.findFirst(sql_);
		setAttr("userInfo",userInfo);
		render(WIEW_WEB+"peo-one.jsp");
	}
	
	//编辑用户信息
	public void editUserInfo(){
		String urealname = getPara("urealname");
		String utel = getPara("utel");
		String uid = getPara("uid");
		String usex = getPara("usex");
		String uaddr = getPara("uaddr");
		String uemail = getPara("email");
		UserBean user = getSessionAttr("user");
		String ucode =  user.get("ucode");
		String sql_ = StringUtils.getSql("sql.find.findUserInfoByCode",ucode);
		UserInfoBean userInfo = UserInfoBean.userInfoDao.findFirst(sql_);
		boolean b = userInfo
		            .set("realname", urealname)
		            .set("utel", utel)
		            .set("uid", uid)
		            .set("usex", usex)
		            .set("uaddr", uaddr)
		            .set("email", uemail)
		            .update();
		if(b){
			renderHtml("<script>alert('用户信息编辑成功');history.back();</script>");
		}else{
			renderHtml("<script>alert('用户信息编辑失败');history.back();</script>");
		}
		
	}
	
	//进入用户收获地址管理页面
	@Before(AuthInterceptor.class)
	public void myaddress(){
		UserBean user = getSessionAttr("user");
		String ucode =  user.get("ucode");
		String sql_ = StringUtils.getSql("sql.find.findAddrByUcode", ucode);
		List<AddressBean> list = AddressBean.addressDao.find(sql_);
		setAttr("addresses",list);
		setAttr("size",list.size());
		render(WIEW_WEB+"peo-address.jsp");
	}
	
    //新增地址
	public void addNewAddress(){
		String name = getPara("name");
		String addr = getPara("addr");
		String tel = getPara("tel");
		String gdtel = getPara("gdtel");
		String email = getPara("email");
		String youbian = getPara("youbian");
		UserBean user = getSessionAttr("user");
		String ucode =  user.get("ucode");
		AddressBean address = new AddressBean();
		boolean bool = address
		               .set("adcode", StringUtils.getTimeCode())
		               .set("ucode", ucode)
		               .set("name", name)
		               .set("addr", addr)
		               .set("tel", tel)
		               .set("gdtel", gdtel)
		               .set("email", email)
		               .set("youbian", youbian)
		               .set("adstate", 1)  // 1:可用   0：不可用
		               .save();
		if(bool){
			renderJson("message","true");
			
		}else{
			renderJson("message","false");
		}
	}
	
	//删除地址
	public void delAddress(){
		String adcode = getPara("adcode");
		boolean bool = AddressBean.addressDao.findById(adcode).set("adstate", 0).update();
		if(bool){
			renderJson("message","true");
		}else{
			renderJson("message","false");
		}
	}
	
	//加载留言
	public void myliuyan(){
		String type = "0";
		String ucode = ((UserBean)getSessionAttr("user")).getStr("ucode");
		String select = "select *";
		String sqlExceptSelect = "from tblliuyan tblly where tblly.lyduixiang=? and tblly.ucode=?";
		Integer page = getParaToInt("page");
		if(page == null || "".equals(page)){
			page= 1;
		}
		Page<LiuyanBean> myliuyans = LiuyanBean.liuyanDao.paginate(page, 55, select,sqlExceptSelect,type,ucode);
		setAttr("myliuyans", myliuyans);
		render(WIEW_WEB+"peo-myliuyan.jsp");
	}
	
	//加载我的评论列表
	public void myreview(){
		String odeal4 = "1";//1标识用户已经收到货，这笔订单完成
		String ucode = ((UserBean)getSessionAttr("user")).getStr("ucode");
		String select = "select tblpo.otime,tblp.pname,tblp.pphoto,tblp.pcode";
		String sqlExceptSelect = "from tblporder tblpo inner join tblorderproduct tblop on tblop.ocode=tblpo.ocode and tblpo.odeal4=? and tblpo.ucode=? "+
		                          "inner join tblproduct tblp on tblp.pcode=tblop.pcode";
		Integer page = getParaToInt("page");
		if(page == null || "".equals(page)){
			page= 1;
		}
		Page<Record> myreviews = Db.paginate(page, 55, select,sqlExceptSelect,odeal4,ucode);
		setAttr("myreviews", myreviews);
		render(WIEW_WEB+"peo-myreview.jsp");
	}
	
	
	//获取消费积分
	public void myjifen(){
		String ucode = ((UserBean)getSessionAttr("user")).getStr("ucode");
		String sql_ = StringUtils.getSql("sql.find.findJifenByUcode", ucode);
		XfjfBean xfjfBean = XfjfBean.xfjfDao.findFirst(sql_);
		String odeal4 = "1";//1标识用户已经收到货，这笔订单完成
		String select = "select tblpo.otime,tblp.pname,tblop.psum,tblop.pjifen";
		String sqlExceptSelect = "from tblporder tblpo inner join tblorderproduct tblop on tblop.ocode=tblpo.ocode and tblpo.odeal4=? and tblpo.ucode=? "+
		                          "inner join tblproduct tblp on tblp.pcode=tblop.pcode";
		Integer page = getParaToInt("page");
		if(page == null || "".equals(page)){
			page= 1;
		}
		Page<Record> myxfjf = Db.paginate(page, 55, select,sqlExceptSelect,odeal4,ucode);
		setAttr("myxfjf", myxfjf);
		setAttr("xfjf",xfjfBean);
		render(WIEW_WEB+"peo-myxfjf.jsp");
	}
	
}
